﻿var map, geocoder, marker, marker2, infowidow, info, con, des;
var chon = 0;
var arrmarker = [];
var arrinfo = [];
var arrcontent = [];

function KhoiTao(){
    if (chon == 0){
        var latlng = new google.maps.LatLng(10.8230989, 106.6296638);
        var option = {
            center: latlng,
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('tagBanDo'), option);
    }
}


function LayTheoDiaDiem() {
    var group = document.getElementById("DiaDiems").value;
    var latlng = new google.maps.LatLng(10.7628273, 106.68255139999997);
    var option = {
        center: latlng,
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('tagBanDo'), option);

    $.ajax({
        url: "http://localhost:3669/Service1.svc/Items",
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].Group == group) {
                    if (data[i].Latitude > 0 && data[i].Longitude > 0) {
                        var position = new google.maps.LatLng(data[i].Latitude, data[i].Longitude);
                        var content;
                        content = '<div align="left">';
                        content += '<table width="285" border="0" cellpadding="0" cellspacing="0">';
                        content += '<tr>';
                        content += '<td width="105" height="26" valign="top">Tên Địa Điểm</td>';
                        content += '<td width="180" valign="top">';
                        content += '<input type="text" id="txtTenDiaDiem" readonly="readonly" width="160" value="' + data[i].Ten + '"/>    </td>';
                        content += '</tr>';
                        content += '<tr>';
                        content += '<td height="26" valign="top">Địa Chỉ</td>';
                        content += '<td rowspan="2" valign="top" align="left">';
                        content += '<textarea id="txtDiaChi" width="420" readonly="readonly">' + data[i].Description + '</textarea>    </td>';
                        content += '</tr>';
                        content += '<tr>';
                        content += '<td height="12"></td>';
                        content += '</tr>';
                        content += '<tr>';
                        content += '<td></td>';
                        content += '<td height="26">';
                        content += '<input type="button" id="bnThemVaoDS" value="Thêm Vào Danh Sách" onclick="ThemVaoDS()" />';
                        content += '</td>';
                        content += '</tr>';
                        content += '</table></div>';
                        SetContent(position, content);
                    }
                }
            }
        }
    });
}

function DanhSachDiaDiemChiaSe() {
    var latlng = new google.maps.LatLng(10.7628273, 106.68255139999997);
    var option = {
        center: latlng,
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('tagBanDo'), option);

    $.ajax({
        url: "http://localhost:3669/Service1.svc/PublicItems",
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].Latitude > 0 && data[i].Longitude > 0) {
                    var position = new google.maps.LatLng(data[i].Latitude, data[i].Longitude);
                    var content;
                    content = '<div align="left">';
                    content += '<table width="285" border="0" cellpadding="0" cellspacing="0">';
                    content += '<tr>';
                    content += '<td width="105" height="26" valign="top">Tên Địa Điểm</td>';
                    content += '<td width="180" valign="top">';
                    content += '<input type="text" id="txtTenDiaDiem" readonly="readonly" width="160" value="' + data[i].Ten + '"/>    </td>';
                    content += '</tr>';
                    content += '<tr>';
                    content += '<td height="26" valign="top">Địa Chỉ</td>';
                    content += '<td rowspan="2" valign="top" align="left">';
                    content += '<textarea id="txtDiaChi" width="420" readonly="readonly">' + data[i].Description + '</textarea>    </td>';
                    content += '</tr>';
                    content += '<tr>';
                    content += '<td height="12"></td>';
                    content += '</tr>';
                    content += '<tr>';
                    content += '<td></td>';
                    content += '<td height="26">';
                    content += '<input type="button" id="bnThemVaoDS" value="Thêm Vào Danh Sách" onclick="ThemVaoDS()" />';
                    content += '</td>';
                    content += '</tr>';
                    content += '</table></div>';
                    SetContent(position, content);
                }

            }
        }
    });
}

function DanhSachDiaDiemTrongTaiKhoan() {
}


function SetContent(pos, con) {
    var mar = new google.maps.Marker({
        map: map,
        position: pos
    });

    google.maps.event.addListener(mar, 'click', function () {
        if (infowidow)
            infowidow.close();
        infowidow = new google.maps.InfoWindow();

        infowidow.setContent(con);
        infowidow.open(map, mar);
    });
}

function ThemVaoDS() {
}



function TimViTriGanNhat() {
        var initialLocation;
        var browserSupportFlag = new Boolean();
        var myOptions = {
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP 
        };
        var lat;
        var lng;
        var b;
        map = new google.maps.Map(document.getElementById('tagBanDo'), myOptions);
        marker = new google.maps.Marker({
            map: map,
            draggable: true,
            animation: google.maps.Animation.DROP
        });
        infowidow = new google.maps.InfoWindow(); 
        // Try W3C Geolocation (Preferred)
        if (navigator.geolocation) {
            browserSupportFlag = true;
            navigator.geolocation.getCurrentPosition(function (position) {
                initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                lat = position.coords.latitude;
                lng = position.coords.longitude;
                map.setCenter(initialLocation);
                marker.setPosition(initialLocation);
            }, function () {
                browserSupportFlag = false;
                handleNoGeolocation(browserSupportFlag);
            });
            } else if (google.gears) {
            browserSupportFlag = true;
            var geo = google.gears.factory.create('beta.geolocation');
            geo.getCurrentPosition(function (position) {
                initialLocation = new google.maps.LatLng(position.latitude, position.longitude);
                lat = position.latitude;
                lng = position.longitude;
                map.setCenter(initialLocation);
                marker.setPosition(initialLocation);
            }, function () {
                handleNoGeoLocation(browserSupportFlag);
            });        
        } else {
            browserSupportFlag = false;
            handleNoGeolocation(browserSupportFlag);
        }
        
        function handleNoGeolocation(errorFlag) {
            var latlng = new google.maps.LatLng(10.7651830206628, 106.67795419693);
            map.setCenter(latlng);
            marker.setPosition(latlng);
            con = 'Trình duyệt không có hỗ trợ Geolocation';
        }

        if (browserSupportFlag) {
                $.ajax({
                    url: "http://localhost:3669/Service1.svc/DiaDiem",
                    success: function (data) {
                        laydata(data);
                    }
                });
                function laydata(data) {
                    con = 'Vị Trí Hiện Tại của bạn là ở đây<br/>';
                    con += 'Bạn Muốn Lấy Địa Điểm Gần Nhất Là<br/><br/>';
                    con += '<select id="sDiaDiem">';
                    for (var i = 0; i < data.length; i++) {
                        con += '<option value="' + data[i].Group;
                        con += '">' + data[i].Description;
                        con += '</option>';
                    }
                    con += '</select>&nbsp;&nbsp';
                    con += '<input type="button" id="bnTimViTri" value="Tìm Vị Trí" onclick="TimViTri()"/>';
                    infowidow.setContent(con);
                    infowidow.open(map, marker);
                    google.maps.event.addListener(marker, 'click', function () {
                        infowidow.setContent(con);
                        infowidow.open(map, marker);
                    });   
                }        
        }   
}

function TimViTri() {
    var group = document.getElementById('sDiaDiem').value;
    var min = 0;
    var lat, long, des;
    if (marker != null) {
        $.ajax({
            url: "http://localhost:3669/Service1.svc/Items",
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].Group == group) {
                        var p1 = marker.getPosition;
                        var p2 = new google.maps.LatLng(data[i].Latitude, data[i].Longitude);
                        rad = function (x) { return x * Math.PI / 180; }
                        distHaversine = function (p1, p2) {
                            var R = 6371; // earth's mean radius in km
                            var dLat = rad(p2.lat() - p1.lat());
                            var dLong = rad(p2.lng() - p1.lng());

                            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                            Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
                            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                            var d = R * c;
                            return d.toFixed(3);
                        }

                        if (min == 0) {
                            min = distHaversine;
                            lat = data[i].Latitude;
                            long = data[i].Longitude;
                            des = data[i].Description;
                        } else if (distHaversine > min) {
                            min = distHaversine;
                            lat = data[i].Latitude;
                            long = data[i].Longitude;
                            des = data[i].Description;
                        }
                    }
                }
                if (marker2 != null) {
                    marker2.setMap(null);
                }
                marker2 = new google.maps.Marker({
                    map: map,
                    position: new google.maps.LatLng(lat, long),
                    animation: google.maps.Animation.DROP
                });
                info = new google.maps.InfoWindow();
                info.setContent(des);
                info.open(map, marker2);
                google.maps.event.addListener(marker2, 'click', function () {
                    info.setContent(des);
                    info.open(map, marker2);
                });
            }
        });
    }
}


function Them() {
    var item = LayItem();
    var json = JSON.stringify(item);
    $.ajax({
        url: 'http://localhost:3669/Service1.svc/ThemItem',
        type : 'POST',
        dataType : 'json',
        data : json,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
        },
        error : function(data){
            alert(data);
        }
    });
}

function LayItem() {
    var id = 0;
    var ten = document.getElementById('txtTenDiaDiem').value;
    var description = document.getElementById('txtDiaChi').value;
    var tinhTrang;
    var ckbox = document.getElementById('ckChiaSe');
    if (ckbox.checked) {
        tinhTrang = "public";
    } else {
        tinhTrang = "private";
    }

    var pos = marker.getPosition();
    var longitude = pos.lng();
    var latitude = pos.lat();
    var group = document.getElementById('GroupDiaDiem').value;
    return {Id : id, Ten : ten, Description : description, TinhTrang : tinhTrang, Longitude : longitude, Latitude : latitude, Group : group};
}

function TimKiem() {
    var address = document.getElementById('txtSearch').value;
    if (!geocoder) {
        geocoder = new google.maps.Geocoder();
    }
    var geocoderRequest = { address: address }

    geocoder.geocode(geocoderRequest, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            map.setZoom(15);
            if (!marker) {
                marker = new google.maps.Marker({
                    map: map
                });
            }
            marker.setPosition(results[0].geometry.location);
            if (!infowidow) {
                infowidow = new google.maps.InfoWindow();
            }
            var content;
            //content = '<strong>' + results[0].formatted_address + '</strong><br/>';
            //            content += '<a href="QuanLyDiaDiem.aspx?action=Them&description='+results[0].formatted_address;
            //            content += '&longitude=' + results[0].geometry.location.lng() + '&latitude=' + results[0].geometry.location.lat() + '">Thêm</a>';

            $.ajax({
                url: "http://localhost:3669/Service1.svc/DiaDiem",
                success: function (data) {
                    laydata(data);
                }
            });
            function laydata(data) {
                content = '<div align="left">';
                content += '<table width="285" border="0" cellpadding="0" cellspacing="0">';
                content += '<tr>';
                content += '<td width="105" height="26" valign="top">Tên Địa Điểm</td>';
                content += '<td width="180" valign="top">';
                content += '<input type="text" id="txtTenDiaDiem" width="160"/>    </td>';
                content += '</tr>';
                content += '<tr>';
                content += '<td height="26" valign="top">Địa Chỉ</td>';
                content += '<td rowspan="2" valign="top">';
                content += '<textarea id="txtDiaChi" width="420" readonly="readonly">' + results[0].formatted_address + '</textarea>    </td>';
                content += '</tr><br/>';
                content += '<tr>';
                content += '<td height="9"></td>';
                content += '</tr>';
                content += '<tr>';
                content += '<td height="26" valign="top">Địa Điểm</td>';
                content += '<td height="26" valign="top">';
                content += '<select id="GroupDiaDiem">';
                for (var i = 0; i < data.length; i++) {
                    content += '<option value="' + data[i].Group;
                    content += '">' + data[i].Description;
                    content += '</option>';
                }
                content += '</select>    </td>';
                content += '</tr>';
                content += '<tr>';
                content += '<td height="26" valign="top">Chia Sẻ</td>';
                content += '<td valign="top">';
                content += '<input type="checkbox" id="ckChiaSe"/>    </td>';
                content += '</tr>';
                content += '<tr>';
                content += '<td height="26" valign="top"></td>';
                content += '<td valign="top">';
                content += '<input type="button" id="bnThem" value="Thêm" onclick="Them()"/>';
                content += '</td>';
                content += '</tr>';
                content += '</table></div>';
                infowidow.setContent(content);
                infowidow.open(map, marker);
            }
            google.maps.event.addListener(marker, 'click', function () {
                infowidow.open(map, marker);
            });
        } else {
            chon = 0;
            KhoiTao();
            alert("Không tìm thấy địa chỉ");
        }
    });
}

function ChonDiaDiem(id, lat, lgt, address) {
    var latlng = new google.maps.LatLng(lat, lgt);
    if (map != null) {
        map.setCenter(latlng);
        map.setZoom(18);
    } else {
        var option = {
            center: latlng,
            zoom: 18,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        try {
            map = new google.maps.Map(document.getElementById('tagBanDo'), option);
        } catch (errr) {
        }
    }

    if (marker == null) {
        marker = new google.maps.Marker({ map: map });
    }
    marker.setPosition(latlng);

    if (infowidow == null) {
        infowidow = new google.maps.InfoWindow();
    }
    var content = address + '<br/>';
    content += '<a href="QuanLyDiaDiem.aspx?action=CapNhat&id=' + id + '">Cập Nhật</a>';
    infowidow.setContent(content);
    infowidow.open(map, marker);
    google.maps.event.addListener(marker, 'click', function () {
        infowidow.open(map, marker);
    });
    chon = 1;
}


